from dataclasses import dataclass
from enum import Enum, unique
from typing import Any

from fastapi.encoders import jsonable_encoder
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, DateTime, TIMESTAMP, text, func
from datetime import datetime

from app.utils.json_utils import custom_encoder
from app.utils.str_utils import str_prominent
from app.utils.time_utils import now_time

Base = declarative_base()

class DictRaw:
    listClass:str= 'primary' #success primary danger

@dataclass
class DictData:
    value: Any
    label: str
    raw: DictRaw #前端显示的样式
    def __init__(self,value,label,raw=DictRaw()):
        self.label=label
        self.value=value
        self.raw=raw

class BaseEnum(Enum):

    @property
    def dictValue(self):
        return self.value.value

    def get_value_label_use_msg(self):
        return f'{self.value.value}[{self.value.label}]'

    @classmethod
    def getLabel(cls,value):
        for member in cls:
            if member.value.value == value:
                return member.value.label
        return value

    @classmethod
    def getValueLabelUseMsg(cls,value):
        for member in cls:
            if member.value.value == value:
                return f'{member.value.value}[{member.value.label}]'
        return value

@unique
class BaseEnumEnabledDisabled(BaseEnum):
    ENABLED = DictData('enabled', '启用')
    DISABLED = DictData('disabled', '禁用')

@unique
class BaseEnumYesNo(BaseEnum):
    YES = DictData('YES', '是')
    NO = DictData('NO', '否')

class TimestampMixin:
    #DateTime  TIMESTAMP
    # created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False)
    # updated_at = Column(TIMESTAMP, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    created_at = Column(TIMESTAMP,comment="创建时间",default=now_time, server_default=text('CURRENT_TIMESTAMP'), nullable=False)
    updated_at = Column(DateTime, comment="更新时间",default=now_time,  onupdate=now_time,server_default=text('CURRENT_TIMESTAMP'),  nullable=False)


    def to_dict(self) -> dict:
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict

    def to_dict_use_result(self) -> dict:
        model_dict =self.to_dict()
        return model_dict

    def json_encoders(self):
        # print(str_prominent('json_encoders'))
        model_dict=self.to_dict_use_result()
        return jsonable_encoder(model_dict, custom_encoder=custom_encoder)
